package com.base.common.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 分离锁。
 * 
 * 使用方式:
 * 
 * <code>
 * SplitReentrantLock locks = new SplitReentrantLock(16);<br>
 *  Lock lock =locks.getLock(key); <br>
 *  lock.lock();<br>
 *  try{<br> 
 *  }finally{ <br>
 *  lock.unlock(); }
 *  </code>
 * 
 * @author yanjiaqiang
 * @date 2010-9-29
 * @version $Id: SplitLock.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class SplitLock {

	private Lock[] locks;

	private int LOCK_NUM;

	public SplitLock(int lockNum) {
		super();
		LOCK_NUM = lockNum;
		locks = new Lock[LOCK_NUM];
		for (int i = 0; i < LOCK_NUM; i++) {
			locks[i] = new ReentrantLock();
		}
	}

	/**
	 * 获取锁, 使用HashMap的hash算法
	 * 
	 * 
	 * @param key
	 * @return
	 */
	public Lock getLock(Object key) {
		int hash = hash(key.hashCode());
		int lockIndex = hash & (LOCK_NUM - 1);
		return locks[lockIndex];
	}

	int hash(int h) {
		h ^= (h >>> 20) ^ (h >>> 12);
		return h ^ (h >>> 7) ^ (h >>> 4);
	}

}
